package net.cyl.util;

import com.google.common.hash.Hashing;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.*;

@Slf4j
public class CommonUtil {

    /**
     * 获取客户端 IP 地址
     *
     * @param request HttpServletRequest 对象
     * @return 客户端 IP 地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的 IP
                    try {
                        InetAddress inet = InetAddress.getLocalHost();
                        ipAddress = inet.getHostAddress();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 对于通过多个代理的情况，第一个 IP 为客户端真实 IP，多个 IP 按照 ',' 分割
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }

    /**
     * 获取全部请求头
     *
     * @param request HttpServletRequest 对象
     * @return 包含所有请求头的 Map
     */
    public static Map<String, String> getAllRequestHeader(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> map = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            // 根据名称获取请求头的值
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * MD5 加密
     *
     * @param data 待加密的字符串
     * @return 加密后的字符串（大写），加密失败返回 null
     */
    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString().toUpperCase();
        } catch (Exception exception) {
            return null;
        }
    }

    /**
     * 获取验证码随机数
     *
     * @param length 随机数的长度
     * @return 指定长度的随机数字符串
     */
    public static String getRandomCode(int length) {
        String sources = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < length; j++) {
            sb.append(sources.charAt(random.nextInt(sources.length())));
        }
        return sb.toString();
    }

    /**
     * 获取当前时间戳
     *
     * @return 当前时间的毫秒数
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis();
    }

    /**
     * 生成 UUID
     *
     * @return 去除横线且截取前 32 位的 UUID 字符串
     */
    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    /**
     * 获取指定长度的随机字符串
     *
     * @param length 字符串的长度
     * @return 指定长度的随机字符串
     */
    private static final String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static String getStringNumRandom(int length) {
        // 生成随机数字和字母
        Random random = new Random();
        StringBuilder saltString = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            saltString.append(ALL_CHAR_NUM.charAt(random.nextInt(ALL_CHAR_NUM.length())));
        }
        return saltString.toString();
    }

    /**
     * 响应 JSON 数据给前端
     *
     * @param response HttpServletResponse 对象
     * @param obj      要响应的对象
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj) {
        response.setContentType("application/json;charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(JsonUtil.obj2Json(obj));
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("响应 json 数据给前端异常: {}", e.getMessage());
        }
    }




    public static void sendHtmlMessage(HttpServletResponse response, JsonData jsonData) {

        response.setContentType("text/html; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.write(jsonData.getData().toString());
            writer.flush();
        } catch (IOException e) {
            log.warn("响应json数据给前端异常:{}", e);
        }
    }
    /**
     * 使用MurmurHash3算法计算字符串的哈希值
     * 该算法以其良好的分布性和高效性被广泛用于哈希表、分布式系统中
     *
     * @param param 需要计算哈希值的字符串
     * @return 计算得到的哈希值，以long类型返回
     */
    public static long murmurHash32(String param){
        long murmurHash32 = Hashing.murmur3_32().hashUnencodedChars(param).padToLong();
        return murmurHash32;
    }

    /**
     * 为URL添加自定义前缀
     * 这个方法通常用于生成唯一的URL标识符，以便在分布式系统或网络应用中使用
     *
     * @param url 原始URL
     * @return 添加前缀后的URL，格式为“雪花算法生成的ID&原始URL”
     */
    public static String addUrlPrefix(String url){
        return IDUtil.generateSnowflakeKey()+"&"+url;
    }

    /**
     * 移除URL中的自定义前缀
     * 这个方法通常用于处理接收到的带有自定义前缀的URL，以提取原始URL信息
     *
     * @param url 带有自定义前缀的URL
     * @return 移除前缀后的原始URL
     */
    public static String removeUrlPrefix(String url){
        return url.substring(url.indexOf("&")+1);
    }

    public static String addUrlPrefixVersion(String url){
        String version = url.substring(0,url.indexOf("&"));

        String originalUrl = url.substring(url.indexOf("&")+1);

        Long newVersion = Long.parseLong(version) + 1;

        return newVersion+"&"+originalUrl;
    }
}